package com.asa.ui.frame;

import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import com.asa.ui.spirit.Circle;
/**
 * 封装mvc
 * @author Administrator
 *
 */
public class AlgoVisualizer {

	private Circle[] circles;
	private AlgoFrame frame;
	
	public AlgoVisualizer(final int sceneWidth,final int sceneHeight,int N) {
		super();
		
		
		
		circles = new Circle[N];
		int R = 50;
		for (int i = 0; i < N; i++) {
			
			int x = (int) (Math.random()*(sceneWidth - 2*R)+R);
			int y = (int) (Math.random()*(sceneHeight - 2*R)+R);
			int vx = (int) (Math.random()*11-5);
			int vy = (int) (Math.random()*11-5);
			circles[i] = new Circle(x, y, R, vx, vy);
					
		}
		
		EventQueue.invokeLater(new Runnable() {//用java事件分发（开了个线程）的方法来创建对话框
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				frame = new AlgoFrame("wellcome", sceneWidth, sceneHeight);
				frame.addKeyListener(new AlgoKeyListener());
				frame.addMouseListener(new AlgoMouseListener());
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						runmiage();
					}

					
				}).start(); ;
			
				
			}
		});

		
		
	}
	
	private void runmiage() {
		while(true) {
			
			//绘制数据
			frame.render(circles);
			AlgoVisHelper.pause(20);
			//更新数据
			if (isAnimated) {
				for (int i = 0; i < circles.length; i++) {
					circles[i].move(0,0,frame.getCanvasWidth(),frame.getCanvasHeight(),circles,i);
				}
			}
			
			
			
		}
	}
	
	
	boolean isAnimated;
	private class AlgoKeyListener extends KeyAdapter{

	
		@Override
		public void keyReleased(KeyEvent event) {
			// TODO Auto-generated method stub
			super.keyReleased(event);
			if (event.getKeyChar()==' ') {
				isAnimated = !isAnimated;
			}
		
		}
		
	}
	
	private class AlgoMouseListener extends MouseAdapter{
		
		
		@Override
		public void mousePressed(MouseEvent event) {
			// TODO Auto-generated method stub
//			System.out.println(frame.getBounds().height );
//			System.out.println(frame.getCanvasHeight());
//			event.translatePoint(0, -(frame.getBounds().height-frame.getCanvasHeight()));
////			e.translatePoint(0, -(20 ));
//			System.out.println(-(frame.getBounds().height - frame.getCanvasHeight()));
//			
//			System.out.println(event.getPoint());
			
			event.translatePoint(0, -(frame.getBounds().height-frame.getCanvasHeight()));
			  //对符合坐标的圆进行颜色改变
			  for(Circle circle:circles){
				  if(circle.contains(event.getPoint())){
					  circle.isFilled=!circle.isFilled;
				  }
			  }

			
		}
		
	}
	
	
	
	
	
	
	
}
